package ex1;

import java.io.*;
import java.net.*;

/*
  This is the client side of the TCP client/server example
  It reads a string in from the console, sends it to the
  server to be converted into upper case, and then prints
  out the result
*/

class TCPClient {
    public static void main (String args[])
      throws Exception
      /* if you have time at the end take a look at the exceptions that might be raised and think about nicer ways of handling them */
      {
	String sentence;
	String modifiedSentence;

	// prepare to get input from the console
	// A BufferedReader provides nice methods like readLine()
	// and is more efficient than just using InputStreamReader
	BufferedReader inFromUser =
	    new BufferedReader(new InputStreamReader(System.in));

	// create the client socket
	// This is just a generic Socket object - we need to specify
	// the address (or name) of machine running your server,
	// plus the port number your server is listening on
	// if this method doesn't throw an exception, then we have
	// successfully opened a connection to the server
	// If you get an error like "connection refused", then the
	// server probably isn't running
	Socket clientSocket = new Socket("127.0.0.1", 4321);

	// a DataOutputStream is a portable way of feeding Java types
	// into something that expects a stream of bytes (a socket doesn't
	// know about strings/ints etc, it just sees bytes)
	// Java IO is ridiculously complicated ...
	DataOutputStream outToServer =
	    new DataOutputStream(clientSocket.getOutputStream());

	// BufferedReader gives us the readLine() method, and an
	// InputStreamReader decodes bytes into characters
	BufferedReader inFromServer =
	    new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

	// read the actual sentence from the console
	System.out.print("Type something: ");
	sentence = inFromUser.readLine();

	// write a stream of bytes to the socket
	// we need the end-of-line character so the server knows when
	// the client has stopped sending (actually so the readLine()
	// method works)
	outToServer.writeBytes(sentence + "\n");
	
	// get the response from the server - this method waits until
	// the server has sent a whole string
	modifiedSentence = inFromServer.readLine();

	System.out.println(modifiedSentence);

	// close the socket and the connection
	clientSocket.close();
    }
}
